package com.sinosun.autotestmachine.tools.reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.sinosun.autotestmachine.App;
import com.sinosun.autotestmachine.tools.parser.FileContentParser;

import android.text.TextUtils;
/**
 * 任务读取器
 * @author HYW
 *
 */
public class InformationReader {
	private static InformationReader instance;	//单例模式
	private Thread localFileReader;
	private Thread netFileReader;
	private static List<String> filePaths = new ArrayList<String>();
	private String testFileDir = null;
	
	//设置任务读取的路径
	public void setTestFileDir(String testFileDir) {
		this.testFileDir = testFileDir;
	}
	
	private InformationReader() {				//带有路径的初始化
		fullFilePath("basecase");				//获取 assert 上所有文件的路径
		for (String ele : filePaths) {			//将指定 assert 路径下的文件复制到 sdCard 上
			try {
				InputStream is = App.getInstance().getApplicationContext().getAssets().open(ele);
		        if (is == null) {
		            return;
		        }
				File outFile = new File(App.getInstance().getTestCasePath() + ele);
				if (!outFile.exists()) {			//无论是否存在都是用最新的测试用例
					outFile.delete();
				}
				outFile.createNewFile();
				OutputStream os = new FileOutputStream(outFile);
				byte buf[] = new byte[is.available()];
			    if (buf != null) {
			    	int len;
			    	while ((len = is.read(buf)) != -1) {
		                os.write(buf, 0, len);
		            }
		        }
		        os.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private int initTestSize() {
		File file;
		if (TextUtils.isEmpty(testFileDir)) {
			file = new File(App.getInstance().getTestCasePath());
		} else {
			file = new File(testFileDir);
		}
		
		int size = 0;
		if (!file.isDirectory()) {
			size++;
		} else {
			size = size + getFolderSize(file);
		}
		return size;
	}
	
	//获取路径文件个数
	private int getFolderSize(File file) {
		String path = file.getAbsolutePath();
		int size = 0;
		for (String f : file.list()) {
			File childFile = new File(path + "/" + f);
			if (childFile.isDirectory()) {
				size = size + getFolderSize(childFile);
			} else {
				size ++;
			}
		}
		return size;
	}
	
	private void fullFilePath(String path) {
		String[] files;
		try {
			files = App.getInstance().getApplicationContext().getAssets().list(path);
			if (files.length > 0) {		//文件夹
				String dir = App.getInstance().getTestCasePath() + path + "/";
				File file = new File(dir);
				if (!file.exists()) {
					file.mkdirs();
				}
				
				for (String ele : files) {
					fullFilePath(path + "/" + ele);
				}
			} else {	//文件
				filePaths.add(path);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private int initFileReadThread() {			//初始化线程
		int testFileSize = initTestSize();
		localFileReader = new Thread() {	//初始化文件线程
			public void run() {
				try {
					readLocalFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		return testFileSize;
	}
	
	private void initNetReadThread() {
		netFileReader = new Thread() {		//初始化网络线程
			public void run() {
				readNetFile();
			}
		};
	}
	
	public void readNetFile() {		//读取网络任务
		NetCaseMaker.getTask();
	}
	
	public void readLocalFile() throws IOException {
		File file;
		if (TextUtils.isEmpty(testFileDir)) {
			file = new File(App.getInstance().getTestCasePath());
		} else {
			file = new File(testFileDir);
		}
		
		if (!file.isDirectory()) {
			readFile(file);
		} else {
			readFolder(file);
		}
	}
	
	private void readFile(File file) throws IOException {		//读取文件数据内容
		BufferedReader br = new BufferedReader(new FileReader(file));
		String fileContent = new String();		//局部变量，执行完函数内容被清理
		String tmpStr;
		while((tmpStr = br.readLine()) != null) {
			fileContent = fileContent + tmpStr;
		}
		FileContentParser.parser(fileContent, new String(""));	//将读取到的文件内容交由解析器处理
		br.close();
	}
	
	private void readFolder(File file) throws IOException {		//读取文件夹的数据内容
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				readFolder(files[i]);		//递归读取
			} else {
				readFile(files[i]);
			}
		}
	}
	
	public static synchronized InformationReader getInformationReader() {		//获取 reader 对象
		if (instance == null) {
			instance = new InformationReader();
		}
		return instance;
	}
	
	public int start(ReadMode mode) {		//开启线程
		int ret = 0;				//返回将要读取到的文件个数
		switch(mode)
		{
		case FILE:
			try {
				ret = initFileReadThread();
				localFileReader.start();
			} catch (IllegalThreadStateException  itse) {
				itse.printStackTrace();
			}
			break;
		case NETWORK:
			try {
				initNetReadThread();
				netFileReader.start();
			} catch (IllegalThreadStateException  itse) {
				itse.printStackTrace();
			}
			break;
		case FILE_NETWORK:
			try {
				netFileReader.start();
			} catch (IllegalThreadStateException  itse) {
				itse.printStackTrace();
			}
			try{
				localFileReader.start();
			} catch (IllegalThreadStateException  itse) {
				itse.printStackTrace();
			}
			break;
		default:
			break;
		}
		return ret;
	}
	
	public void stop() {		//关闭文件+网络线程
		stop(ReadMode.FILE_NETWORK);
	}
	
	public void stop(ReadMode mode) {
		switch(mode)
		{
		case FILE:
			localFileReader.interrupt();
			break;
		case NETWORK:
			netFileReader.interrupt();
			break;
		case FILE_NETWORK:
			netFileReader.interrupt();
			localFileReader.interrupt();
			break;
		default:
			break;
		}
	}
}
